<template>
  <div class="app-container calendar-list-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleUpdate">修改</el-button>
      <!-- <el-button class="filter-item" type="primary" @click="exchangeIntegral">爱币兑换积分</el-button> -->
    </div>

    <!-- 机构信息 -->
    <el-card class="box-card">
      <h3>机构信息</h3>
      <el-form ref="instituteForm" :model="instituteForm" label-position="right" label-width="100px">
        <el-form-item label="机构名称:" prop="name">
          <span v-text="instituteForm.name" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="机构简介:" prop="nickName">
          <span v-text="instituteForm.nickName" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="机构经度:" prop="longitude">
          <span v-text="instituteForm.longitude" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="机构纬度:" prop="latitude">
          <span v-text="instituteForm.latitude" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="机构类型:" prop="mechanismType">
          <span v-text="instituteForm.mechanismType" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="支付宝账号:" prop="alpay">
          <span v-text="instituteForm.alpay" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="微信账号:" prop="wechat">
          <span v-text="instituteForm.wechat" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="具体位置:" prop="address">
          <span v-text="(instituteForm.province + instituteForm.city + instituteForm.area + instituteForm.address)==='undefined'?'':(instituteForm.province + instituteForm.city + instituteForm.area + instituteForm.address)" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="法人:" prop="legalPerson">
          <span v-text="instituteForm.legalPerson" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="联系号码:" prop="telephone">
          <span v-text="instituteForm.telephone" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <el-form-item label="激活时间" prop="startTime">
          <span v-text="instituteForm.startTime" style="color:#4876ff;">
          </span>
        </el-form-item>
        <el-form-item label="到期时间" prop="endTime">
          <span v-text="instituteForm.endTime" style="color:#4876ff;">
          </span>
        </el-form-item>
        <el-form-item label="积分总额:" prop="integralAmountAll">
          <el-tag type="danger">
            {{instituteForm.integralAmountAll}}
          </el-tag>
          <el-tag type="warning">超出总额度将收取1%的手续费</el-tag>
        </el-form-item>
        <el-form-item label="已用额度:" prop="integralAmountUsed">
          <el-tag type="success">
            {{instituteForm.integralAmountUsed}}
          </el-tag>
        </el-form-item>
        <el-form-item label="爱币余额:" prop="balance">
          <span v-text="balance" style="color:#3cd94f;">
          </span>
        </el-form-item>
        <!-- <el-form-item label="机构图片:"> -->
        <!-- <el-upload class="avatar-uploader" :headers="headers" :action='uploadPath' width="100" height="100" list-type="picture-card" :show-file-list="false" accept=".jpg,.jpeg,.png,.gif" :on-success="uploadPicUrl"> -->
        <!-- <img v-if="instituteForm.qualifications" :src="instituteForm.qualifications" class="avatar"> -->
        <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
        <!-- </el-upload> -->
        <!-- </el-form-item> -->
        <el-form-item label="宣传画廊">
          <!-- <img v-for="instituteForm.qualifications" :src="instituteForm.qualifications" class="avatar"> -->
          <img class="avatar" v-for="pic in instituteForm.qualifications" :key="pic" :src="pic" />
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 爱币兑换积分对话框 -->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisibles">
      <el-form :rules="rules" ref="userForm" :model="userForm" status-icon label-position="left" style='width: 400px; margin-left:50px;'>
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="userForm.username" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" label-width="100px">
          <el-input v-model="userForm.mobile" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="爱币余额" prop="balance" label-width="100px">
          <el-input v-model="userForm.balance" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="积分余额" prop="integral" label-width="100px">
          <el-input v-model="userForm.integral" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="请输入要兑换为积分的爱币数量" prop="exchangeNum" :readonly="true">
          <el-input v-model="userForm.exchangeNum"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">返回</el-button>
        <el-button type="primary" @click="exchangeData">兑换</el-button>
      </div>
    </el-dialog>
    <!-- 修改和添加对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="dataForm.name" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="机构简介" prop="nickName">
          <el-input v-model="dataForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="机构经度:" prop="longitude">
          <el-input v-model="dataForm.longitude"></el-input>
        </el-form-item>
        <el-form-item label="机构纬度:" prop="latitude">
          <el-input v-model="dataForm.latitude"></el-input>
        </el-form-item>
        <el-form-item label="机构类型" prop="mechanismType">
          <el-input v-model="dataForm.mechanismType"></el-input>
        </el-form-item>
        <el-form-item label="支付宝PID" prop="AlPay">
          <el-input v-model="dataForm.alpay"></el-input>
        </el-form-item>
        <div style="font-size:12px;color:red;width:900px;margin-bottom:20px">支付宝合作伙伴身份(PID)查询地址:<a href="https://openhome.alipay.com/platform/keyManage.htm?keyType=partner" style="color:blue;">https://openhome.alipay.com/platform/keyManage.htm?keyType=partner</a></div>
        <!-- <el-form-item label="微信账号" prop="WeChat">
          <el-input v-model="dataForm.wechat"></el-input>
        </el-form-item> -->
        <el-form-item label="区域地址">
          <el-select v-model="dataForm.provinceId" placeholder="省" @change="provinceChange">
            <el-option v-for="item in provinces" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.cityId" placeholder="市" @change="cityChange">
            <el-option v-for="item in cities" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.areaId" placeholder="市" @change="areaChange">
            <el-option v-for="item in areas" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-show="false" v-model="dataForm.areaId" placeholder="s" @change="areasChange">
            <el-option v-for="item in areass" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体位置" prop="address">
          <el-input v-model="dataForm.address"></el-input>
        </el-form-item>
        <el-form-item label="法人" prop="legalPerson">
          <el-input v-model="dataForm.legalPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系号码" prop="telephone">
          <el-input :disabled="true" v-model="dataForm.telephone"></el-input>
        </el-form-item>
        <!-- <el-form-item label="机构图片" prop="qualifications">
          <el-upload class="avatar-uploader" :headers="headers" :action="uploadPath"  list-type="picture-card" :show-file-list="false" accept=".jpg,.jpeg,.png,.gif" :on-success="uploadPicUrl">
            <img v-if="dataForm.qualifications" :src="dataForm.qualifications" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="宣传画廊">
          <el-upload :action='uploadPath' :headers="headers" :limit='5' multiple accept=".jpg,.jpeg,.png,.gif" :file-list="galleryFileList" list-type="picture-card" :on-exceed='uploadOverrun' :on-success="handleGalleryUrl" :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 200px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}
.avatar {
  width: 140px;
  height: 140px;
  display: block;
}
.gallery {
  width: 80px;
  margin-right: 10px;
  display: block;
}
</style>  

<script>
import { listMechanism, updateMechanism, listUserData, updateBalance } from '@/api/mechanism'
import store from '@/store'
import { listSubRegion } from '@/api/region'
import { createStorage, uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'

export default {
  name: 'Mechanism',
  computed: {
    headers() {
      return {
        'X-Token': getToken()
      }
    }
  },
  data() {
    return {
      uploadPath,
      qualificationsFileList: [],
      galleryFileList: [],
      list: undefined,
      listLoading: true,
      mechanism: { qualifications: [] },
      provinces: {},
      cities: {},
      areas: {},
      areass: {},
      balance: '',
      queryId: {
        queryId: ''
      },
      regionsId: {
        id: 0
      },
      instituteForm: {
        name: undefined,
        nickName: undefined,
        mechanismType: undefined,
        address: undefined,
        legalPerson: undefined,
        telephone: undefined,
        startTime: undefined,
        endTime: undefined,
        qualifications: [],
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        province: undefined,
        city: undefined,
        area: undefined,
        longitude: undefined,
        latitude: undefined,
        alpay: undefined,
        wechat: undefined
      },
      userForm: {
        username: undefined,
        mobile: undefined,
        integral: undefined,
        balance: undefined,
        exchangeNum: undefined
      },
      dataForm: {
        id: undefined,
        name: undefined,
        nickName: undefined,
        mechanismType: undefined,
        address: undefined,
        legalPerson: undefined,
        telephone: undefined,
        qualifications: [],
        integralAmountAll: undefined,
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        street: undefined,
        longitude: undefined,
        latitude: undefined,
        alpay: undefined,
        wechat: undefined
      },
      dialogFormVisible: false,
      dialogFormVisibles: false,
      dialogStatus: '',
      textMap: {
        update: '编辑机构',
        exchange: '爱币兑换积分'
      },
      rules: {
        name: [{ required: true, message: '机构名称不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.downValues()
    this.getProvinces()
  },
  methods: {
    uploadPicUrl: function(response) {
      console.log(response.data.url)
      this.dataForm.qualifications.push(response.data.url)
    },
    handleImport() {
      console.log('handleImport')
    },
    getProvinces() {
      listSubRegion(this.regionsId).then(response => {
        this.provinces = response.data.data
      })
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.dataForm.qualifications.push(response.data.url)
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.dataForm.qualifications.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.dataForm.qualifications[i] === url) {
          this.dataForm.qualifications.splice(i, 1)
        }
      }
    },
    downValues() {
      this.queryId.queryId = store.getters.mechanismId
      listMechanism(this.queryId).then(response => {
        this.instituteForm = response.data.data.mdList
        this.balance = response.data.data.balance
      })
    },
    provinceChange(val) {
      if (val === undefined) {
        return
      }
      this.cities = {}
      this.dataForm.cityId = undefined
      this.areas = {}
      this.dataForm.areaId = undefined
      listSubRegion({ id: val }).then(response => {
        this.cities = response.data.data
      })
    },
    cityChange(val) {
      if (val === undefined) {
        return
      }
      this.areas = {}
      this.dataForm.areaId = undefined
      listSubRegion({ id: val }).then(response => {
        this.areas = response.data.data
      })
    },
    areaChange(val) {
      if (val === undefined) {
        return
      }
      this.areass = {}
      this.dataForm.street = undefined
    },
    areasChange(val) {},
    /* 重置表单 */
    resetForm() {
      this.resetDataForm()
      this.resetUserForm()
    },
    resetDataForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        nickName: undefined,
        mechanismType: undefined,
        address: undefined,
        legalPerson: undefined,
        telephone: undefined,
        startTime: undefined,
        endTime: undefined,
        qualifications: [],
        integralAmountAll: undefined,
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        street: undefined,
        longitude: undefined,
        latitude: undefined
      }
    },
    resetUserForm() {
      this.userForm = {
        username: undefined,
        mobile: undefined,
        integral: undefined,
        balance: undefined,
        exchangeNum: undefined
      }
    },
    uploadAvatar(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorage(formData)
        .then(res => {
          this.dataForm.avatar = res.data.data.url
        })
        .catch(() => {
          this.$message.error('上传失败，请重新上传')
        })
    },
    handleUpdate() {
      this.resetForm()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.dataForm = this.instituteForm
      this.cities = {}
      this.areas = {}
      listSubRegion({ id: this.dataForm.provinceId }).then(response => {
        this.cities = response.data.data
      })
      listSubRegion({ id: this.dataForm.cityId }).then(response => {
        this.areas = response.data.data
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

      this.galleryFileList = []
      for (var i = 0; i < this.dataForm.qualifications.length; i++) {
        this.galleryFileList.push({
          url: this.dataForm.qualifications[i]
        })
      }
    },
    createRecordSn() {
      var date = new Date()
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      var ss = date.getMilliseconds()
      if (ss < 10) {
        ss = '00' + ss
      } else if (ss < 100) {
        ss = '0' + ss
      }
      // var result = Y.to + M + D + h + m + s + ss;
      var result =
        Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString()
      console.log('result = ' + result)
      return result
    },
    /* 更新数据 */
    updateData() {
      // var finalAddress = this.dataForm.province + this.dataForm.city + this.dataForm.area
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.address !== undefined) {
            const ades = this.dataForm.address
            const add = ades.replace(/\s+/g, '')
            var testalpay = /^2088/
            this.dataForm.address = this.cleanSpelChar(add)
            if (!testalpay.test(this.dataForm.alpay)) {
              this.$alert('支付宝PID必须是以2088开头的唯一号，请点击链接获取', '提示', {
                confirmButtonText: '确定'
              })
              return
            }
            updateMechanism(this.dataForm).then(res => {
              if (res.data.data != null) {
                this.dialogFormVisible = false
                // this.instituteForm = res.data.data
                // this.instituteForm.address = finalAddress + res.data.data.address
                this.downValues()
                // this.getProvinces()
                this.resetForm()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 1000
                })
              } else {
                this.$alert('该手机号已经注册商圈用户！', '提示', {
                  confirmButtonText: '确定'
                })
              }
            })
          } else {
            this.$alert('请填写地址', '提示', {
              confirmButtonText: '确定'
            })
          }
        } else {
          this.$notify({
            title: '失败',
            message: '更新失败，请将信息填写完整',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    cleanSpelChar: function(localData) {
      var noiseChar =
        '#$%^&_+-=`[]{};\':"\\|,./<>?\n\r～！＠＃＄％＆＊·‘’¥——＿＋－-()（）＝｀｛｝；＇：＂＼｜，．／“”　'
      var goodChar = ''
      for (var i = 0; i < noiseChar.length; i++) {
        var oneChar = noiseChar.charAt(i)
        var towChar = goodChar
        while (localData.indexOf(oneChar) >= 0) {
          localData = localData.replace(oneChar, towChar)
        }
      }
      return localData
    },
    handleSelectUser(row) {
      console.log(row)
      this.$router.push({ path: '/mechanism/mechanismUser', query: { mechanismId: row.id }})
    },
    exchangeIntegral() {
      this.resetForm()
      this.dialogStatus = 'exchange'
      this.dialogFormVisibles = true
      console.log(this.instituteForm.telephone)
      listUserData({ mobile: this.instituteForm.telephone }).then(response => {
        if (response.data.data == null) {
          this.$alert('当前手机号没有注册用户', '提示', {
            confirmButtonText: '确定'
          })
          this.dialogFormVisibles = false
        } else {
          this.userForm = response.data.data
        }
      })
    },
    exchangeData() {
      this.$confirm('爱币可以兑换积分，积分不可以兑换爱币, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (!/^[0-9]*$/.test(this.userForm.exchangeNum)) {
            this.$alert('请输入数字', '提示', {
              confirmButtonText: '确定'
            })
            this.userForm.exchangeNum = undefined
          } else if (this.userForm.exchangeNum > this.userForm.balance) {
            this.$alert('爱币余额不足', '提示', {
              confirmButtonText: '确定'
            })
          } else if (/^[0]*$/.test(this.userForm.exchangeNum)) {
            this.$alert('不能输入0爱币', '提示', {
              confirmButtonText: '确定'
            })
            this.userForm.exchangeNum = undefined
          } else {
            updateBalance({
              exchangeNum: this.userForm.exchangeNum,
              mobile: this.userForm.mobile,
              recordSn: this.createRecordSn()
            }).then(response => {
              this.userForm = response.data.data
            })
            this.$message({
              type: 'success',
              message: '兑换成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消兑换'
          })
        })
    }
  }
}
</script>
